# # -*- coding: utf-8 -*-
# """
# @Time ： 2020-01-06 10:46
# @Auth ： chenzj85
# @Description：
#
# """
# import shutil
#
# import imageio
#
# from algo.Algo_interface import Algo_interface
# import json
# import sys
# import dlib
# import os
# import glob
# from sklearn.decomposition import PCA
# from sklearn.neural_network import MLPClassifier
# import numpy as np
# import numpy as np
# import cv2
# import random
# import pandas as pd
# # from detectutils import detectutils
# from app.utils.detectutils import detectutils
# from PIL import Image
#
# class FaceDetection(Algo_interface):
#     def __init__(self, model_type, model_name, model_params):
#         self.task_type = model_type
#         self.model_name = model_name
#         self.model_params = model_params
#         self.model = dict()
#         self.build_model()
#         # return self.model
#
#
#     def set_model(self, model):
#         self.model = model
#         return 1
#
#     def get_model(self):
#         return self.model
#
#     def build_model(self):
#
#         if self.model_name == 'hog_detector':
#             self.options = dlib.simple_object_detector_training_options()
#             self.options.add_left_right_image_flips = True
#             self.options.C = 5
#             # Tell the code how many CPU cores yo ur computer has for the fastest training.
#             self.options.num_threads = 4
#             self.options.be_verbose = True
#             # n_components后期改超参,都可以直接由model_params拆解出来，如果换模型另算
#             self.model['model'] = MLPClassifier(random_state=10, hidden_layer_sizes=(128,), solver='adam',
#                                            learning_rate='constant', learning_rate_init=0.001, early_stopping=True)
#
#     def train(self,data):
#         x_train, y_train, xml_train_path = data  # 在api.py是tuple进来的两个Series
#         # what do the outputs of verbose training mean?  In particular, what is the risk and risk gap?
#         dlib.train_simple_object_detector(xml_train_path, "detector.svm", self.options)
#         # save model
#         self.model['dlib'] = dlib.simple_object_detector("detector.svm")
#         x_train = np.asarray(list(map(lambda x: x.flatten(), x_train)))  # 对df内的图像array光栅化并转矩阵
#         n = len(x_train)
#         self.model['pca'] = PCA(n_components=n, whiten=True)
#         x_train_pca = self.model['pca'].fit_transform(x_train)  # fit pca
#         self.model['model'].fit(x_train_pca, y_train)
#
#         return 1
#
#     def predict(self,data):   #data为图片路径list
#         def box_detect(path):
#             data_list = []
#             img = imageio.imread(path, as_gray=False, pilmode="RGB")
#             ##img = imageio.imread(image, as_gray=False, pilmode="RGB") 读取报错时备用
#             dets = self.model['dlib'](img)
#             for k, d in enumerate(dets):
#                 data_list.append([d.left(), d.top(), d.right(), d.bottom()])
#             return data_list
#
#         ##获得box_predict列,作为评估dataframe
#         data['box_predict'] = list(map(lambda x: box_detect(x), data['image_path']))
#
#         ##publish端预测
#         image_path = list(data['image_path'])
#         predict_result = []
#         miss_list = []
#         for path in image_path:
#             boxs = box_detect(path)
#             if len(boxs) > 0:
#                 for box in boxs:
#                     predict_result.append([path, box])
#             else:
#                 miss_list.append(path)
#
#         predict_result = pd.DataFrame(predict_result, columns=['image_path', 'box'])
#         ##调用函数截取图片
#         predict_result['array'] = list(map(lambda x, y: detectutils.shot(x, y), predict_result['image_path'], predict_result['box']))
#         if len(list(predict_result['array'])) < 1:
#             predict_result['pca'] = None
#             predict_result['lable'] = None
#         else:
#         ##数据降维
#             predict_result['pca'] = list(self.model['pca'].transform(np.asarray(list(predict_result['array']))))
#             ##预测lable
#             predict_result['lable'] = list(self.model['model'].predict(np.asarray(list(predict_result['pca']))))
#
#
#         for miss_image in miss_list:
#             predict_result = predict_result.append([{'image_path': miss_image}], ignore_index=True)
#
#         predict_result['image_name'] = list(map(lambda x: os.path.basename(x), predict_result['image_path']))
#         predict_result = predict_result[['image_name', 'box', 'lable']]
#         return (data, predict_result)
#
#
